package hust.iamk.backup;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.widget.Toast;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

public class ServiceUpload extends Service {
	private Context mContext;

	public ServiceUpload() {
		// TODO Auto-generated constructor stub
		mContext = this;
	}

	private AmazonS3Client s3Client = new AmazonS3Client(
			new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
					Constants.SECRET_KEY));

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		ArrayList<String> listUri = new ArrayList<String>();
		Bundle bundle = intent.getExtras();
		if (bundle.get("listUri") instanceof ArrayList<?>) {
			listUri = (ArrayList<String>) bundle.get("listUri");
		}
		// for (String uri : listUri) {
		// // Log.i("URI", " + " + uri.toString());
		// new S3PutObjectTask().execute(Uri.parse(uri));
		// }
		new S3PutObjectTask().execute(listUri);
		stopSelf();
		return Service.START_NOT_STICKY;
	}

	private class S3PutObjectTask extends AsyncTask<List<String>, Void, String> {
		@Override
		protected String doInBackground(List<String>... uris) {
			// TODO Auto-generated method stub
			int count = 0;
			for (String str : uris[0]) {
				if (uris == null || uris.length != 1) {
					return null;
				}
				Uri selectedImage = Uri.parse(str);
				ContentResolver resolver = getContentResolver();
				String fileSizeColumn[] = { OpenableColumns.SIZE,
						MediaStore.MediaColumns.DATA };

				Cursor cursor = resolver.query(selectedImage, fileSizeColumn,
						null, null, null);
				cursor.moveToFirst();

				int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
				int sizePath = cursor
						.getColumnIndex(MediaStore.MediaColumns.DATA);

				String path = cursor.getString(sizePath);
				// Log.d("ServiceUpload", path);

				String size = null;
				if (!cursor.isNull(sizeIndex)) {
					size = cursor.getString(sizeIndex);
				}
				cursor.close();

				ObjectMetadata metadata = new ObjectMetadata();
				metadata.setContentType(resolver.getType(selectedImage));
				if (size != null) {
					metadata.setContentLength(Long.parseLong(size));
				}

				// S3TaskResult result = new S3TaskResult();
				PutObjectRequest por;
				try {
					por = new PutObjectRequest(
							Constants.getPictureBucket(),
							Constants.getAccount(mContext)
									+ "/"
									+ path.split("/")[path.split("/").length - 1],
							resolver.openInputStream(selectedImage), metadata);
					s3Client.putObject(por);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG)
							.show();
					Log.d("Exception", "ex " + e.getMessage());
				}
				count++;
			}
			return " " + count;
		}

		protected void onPostExecute(String result) {
			Toast.makeText(mContext, "Upload Success " + result + "images",
					Toast.LENGTH_LONG).show();
		}
	}

//	private class S3TaskResult {
//		String errorMessage = null;
//		Uri uri = null;
//
//		public String getErrorMessage() {
//			return errorMessage;
//		}
//
//		public void setErrorMessage(String errorMessage) {
//			this.errorMessage = errorMessage;
//		}
//
//		public Uri getUri() {
//			return uri;
//		}
//
//		public void setUri(Uri uri) {
//			this.uri = uri;
//		}
//	}
}
